const e = require('express')
const noticeModel = require('../../model/notice/noticeModel')
class noticeService{
  //获取最新公告
  async getNotice(req,res){
    const {results:data} = await noticeModel.notice()
    if(data.length != 0 ){
      return res.json({
        data:data[0],
        meta: {
          msg: '获取最新公告成功',
          status: 200
        } 
      })
    }else{
      return res.json({
        meta:{
          msg: '获取最新公告失败',
          status: 404
        }
      })
    }
  }
  //公告分页获取
  async getPageNotice(req,res){
    let {pagenum,per_page} = req.query
    pagenum = parseInt(pagenum)
    per_page = parseInt(per_page)
    if(per_page === 1){
      pagenum = pagenum-1
    }else if(per_page === 2){
      pagenum = (pagenum-1)*2
    }else if(per_page === 5){
      pagenum = (pagenum-1)*5
    }else if(per_page === 10){
      pagenum = (pagenum-1)*10
    }
    const Info = await noticeModel.noticeInfo()
    const total_count = Info.results.length
    const {results:data} = await noticeModel.pageNotice(pagenum,per_page)
    if(data.length != 0){
      return res.json({
        total_count,
        pagenum:pagenum+1,
        per_page,
        data
      })
    }else{
      return res.json({
        meta:{
          msg: '公告查询失败',
          status: 404
        }
      })
    }
  }

  //发布公告
  async postAddNotice(req,res){
    let {content,author} = req.body
    const {results:data} = await noticeModel.addNotice(content,author)
    if(data.length != 0){
      return res.json({
        meta:{
          msg: '添加公告成功',
          status: 200
        }
      })
    }else{
      return res.json({
        meta:{
          msg: '添加公告失败',
          status: 404
        }
      })
    }
  }
  //所有公告信息
  async getNoticeInfo(req,res){
    const {results:data} = await noticeModel.noticeInfo()
    if(data.length != 0){
      return res.json({
        data,
        meta:{
          msg: '公告获取成功',
          status: 200
        }
      })
    }else{
      return res.json({
        meta:{
          msg: '公告获取失败',
          status: 404
        }
      })
    }
  }
}

module.exports = new noticeService